package com.lovo.shiro;

import com.lovo.result.Result;
import com.lovo.result.ResultCode;
import com.lovo.service.IUserInfoService;
import com.lovo.util.WebUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)  {
        Subject subject = this.getSubject(request, response);
        try{
            String token = WebUtil.getToken(request);
            subject.login(new JWTToken(token));
        }catch (AuthenticationException e){
            return false;
        }
        return true;

    }
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {
                return this.executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse resp = (HttpServletResponse) response;
            if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
                resp.setStatus(HttpStatus.OK.value());
                return true;
            } else {
                /**
                 * 在这里实现自己想返回的信息，其他地方和源码一样就可以了
                 */
                WebUtil.writeValueAsString(response, Result.fail(ResultCode.USER_AUTHENTICATION_ERROR));
                return false;
            }
        }
    }
}
